package cn.kgc.Thread.work.work05;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class WebSites implements Runnable{
    private  int count = 10; //共10张火车票
    private int num = 0; //记录售出第几张火车票

    //可重入锁
    final Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while(true) {
            lock.lock(); //上锁
            try{
                if(count <= 0) return;
                System.out.println(Thread.currentThread().getName() + "售出第" + (++num) + "票,还剩余" + (--count) + "票。");
                try {
                    Thread.sleep((int)Math.random() * 100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            finally {
                lock.unlock(); //解锁
            }
        }
    }

    public static void main(String[] args) {
        WebSites target = new WebSites();
        /*for (int i = 0; i < 3; i++) {
            new Thread(target,"售票窗口" + (i+1)).start();
        }*/

        Thread win1 = new Thread(target,"窗口1");
        win1.setPriority(Thread.NORM_PRIORITY);
        Thread win2 = new Thread(target,"窗口2");
        win2.setPriority(Thread.NORM_PRIORITY);
        Thread win3 = new Thread(target,"窗口3");
        win3.setPriority(Thread.NORM_PRIORITY);
        win1.start();
        win2.start();
        win3.start();

    }
}
